package io.renren.modules.demo.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONArray;
import io.renren.common.annotation.LogOperation;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.redis.RedisUtils;
import io.renren.common.utils.ExcelDataListener;
import io.renren.common.utils.ExcelUtils;
import io.renren.common.utils.Result;
import io.renren.common.validator.AssertUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.demo.dto.ExcelDataDTO;
import io.renren.modules.demo.excel.ExcelDataExcel;
import io.renren.modules.demo.service.ExcelDataService;
import io.renren.modules.sp.entity.SpPassAccountEntity;
import io.renren.modules.sp.excel.SpPassAccountExcel;
import io.renren.modules.sp.service.SpPassAccountService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;


/**
* Excel导入演示
*
* @author Mark sunlightcs@gmail.com
*/
@RestController
@RequestMapping("demo/excel")
@Api(tags="Excel导入演示")
public class ExcelDataController {
    @Autowired
    private ExcelDataService excelDataService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private SpPassAccountService spPassAccountService;

    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
        @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
        @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    @RequiresPermissions("demo:excel:all")
    public Result<PageData<ExcelDataDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params){
        PageData<ExcelDataDTO> page = excelDataService.page(params);

        return new Result<PageData<ExcelDataDTO>>().ok(page);
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    @RequiresPermissions("demo:excel:all")
    public Result<ExcelDataDTO> get(@PathVariable("id") Long id){
        ExcelDataDTO data = excelDataService.get(id);

        return new Result<ExcelDataDTO>().ok(data);
    }

    @PostMapping
    @ApiOperation("保存")
    @RequiresPermissions("demo:excel:all")
    public Result save(@RequestBody ExcelDataDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);

        excelDataService.save(dto);

        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @RequiresPermissions("demo:excel:all")
    public Result update(@RequestBody ExcelDataDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);

        excelDataService.update(dto);

        return new Result();
    }

    @DeleteMapping
    @ApiOperation("删除")
    @RequiresPermissions("demo:excel:all")
    public Result delete(@RequestBody Long[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");

        excelDataService.delete(ids);

        return new Result();
    }

    @PostMapping("import")
    @ApiOperation("导入")
    @RequiresPermissions("demo:excel:all")
    @ApiImplicitParam(name = "file", value = "文件", paramType = "query", dataType="file")
    public Result importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        //解析并保存到数据库
        EasyExcel.read(file.getInputStream(), ExcelDataExcel.class, new ExcelDataListener<>(excelDataService, null)).sheet().doRead();
        return new Result();
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @RequiresPermissions("demo:excel:all")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<ExcelDataDTO> list = excelDataService.list(params);

        ExcelUtils.exportExcelToTarget(response, null, "Excel导入演示", list, ExcelDataExcel.class);
    }


    /**
     * 直通导入
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("importPassCode")
    @LogOperation("直通导入")
    public Result importProductArea(@RequestParam("file") MultipartFile file) throws Exception {
        List<SpPassAccountEntity> list = new ArrayList<SpPassAccountEntity>();
        //解析并保存到数据库
        try {
            EasyExcel.read(file.getInputStream(), SpPassAccountExcel.class, new ExcelDataListener<>(spPassAccountService, list)).sheet().doRead();
        }catch(Exception e){
            e.printStackTrace();
            //return new Result().error(e.getMessage());
        }
        for (SpPassAccountEntity entity : list) {
            if (StringUtils.isNotEmpty(entity.getMsg())) {
                String errorCode = UUID.randomUUID().toString();
                redisUtils.set(errorCode, JSONArray.toJSONString(list), 1000);
                return new Result().error(errorCode);
            }
        }

        return new Result();
    }

    /**
     * 直通码错误导出
     * @param errorCode
     * @param response
     * @throws Exception
     */
    @GetMapping("exportPassCodeError")
    public void exportProductAreaError(String errorCode,HttpServletResponse response) throws Exception {
        String json = (String) redisUtils.get(errorCode);
        redisUtils.delete(errorCode);
        if (json != null) {
            List<SpPassAccountExcel> list = JSONArray.parseArray(json, SpPassAccountExcel.class);
            ExcelUtils.exportExcelToTarget(response, "直通码错误信息", "sheet", list, SpPassAccountExcel.class);
        }
    }

}
